#include <python.h>
#include <comedilib.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <errno.h>

static comedi_t *dev;
static void *map;
static comedi_cmd command;
static unsigned int channelList[2];
static int size;
static unsigned int back = 0;
static unsigned int front = 0;

static PyObject * initialize_daq(PyObject *self, PyObject *args) {
	dev = comedi_open("/dev/comedi0");
  	if(!dev) {
    		printf("Could not open device!");
    		//need to throw python exception here
  	}
  	
  	map=mmap(NULL,size,PROT_READ,MAP_SHARED,comedi_fileno(dev),0);
  	fprintf(stderr,"map=%p\n",map);
	if( map == MAP_FAILED ){
		perror( "mmap" );
		exit(1);
	}
	
	size = comedi_get_buffer_size(dev,0);
	
  	//CR_PACK(channel, range, diff)
  	channelList[0]= CR_PACK(0, 0, AREF_DIFF);
  	channelList[1]= CR_PACK(0, 0, AREF_DIFF);
  	
  	//comedi_get_cmd_generic_timed(dev, subdev, command, periodInNs)
  	comedi_get_cmd_generic_timed(dev, 0, &command, 10000000);
  	command.scan_end_arg = 2; //num of channels
	
	//continuous acquisition
	command.stop_src = TRIG_NONE;
  	command.stop_arg = 0;

	//non-continuous acquisition
  	//command->stop_src = TRIG_COUNT;
  	//command->stop_arg = configfile->SamplesPerChannel;

  	command.chanlist = channelList;
  	command->chanlist_len = 2;

  	int isValid = comedi_command_test(dev, &command);
  	if(isValid<0) {
    		printf("First command not valid.\n");
  	}
  	isValid = comedi_command_test(dev, &command);
  	if(isValid<0) {
    		printf("Second command not valid.\n");
  	}
  	
  	//return an int of one for success
    return Py_BuildValue("i", 1);
}

static PyObject * start(PyObject *self, PyObject *args) {
	int ret = comedi_command(dev, &command);
	if(ret<0) {
    		printf("Could not execute command...exiting...\n");
  	}
	return Py_BuildValue("i", ret);
}

static PyObject * get_results(PyObject *self, PyObject *args) {
		front += comedi_get_buffer_contents(dev,0);
		if(front<back)
			break;
		if(front==back){
			break;
		}

		for(i=back;i<front;i+=sizeof(sampl_t)){
			static int col = 0;
			printf("%d ",*(sampl_t *)(map+(i%size)));
			col++;
			if(col==2){
				printf("\n");
				col=0;
			}
		}

		ret = comedi_mark_buffer_read(dev,0,front-back);
		if(ret<0){
			comedi_perror("comedi_mark_buffer_read");
			break;
		}
		back = front;
		return Py_BuildValue("i", 1);
}